//
//  PrivateListViewController.m
//  fitnessmanage
//
//  Created by wujian on 2018/1/24.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//

#import "PrivateListViewController.h"
#import "AppointPrivateClassTableViewCell.h"
#import "CourseModel.h"
#import "HDAlertView.h"
#import "MOFSPickerManager.h"
#import "SelectMemberViewController.h"
#import "UserNavigationController.h"
#import "TeachPrivateClassViewController.h"
#import "CoursesClassTableViewCell.h"

@interface PrivateListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,strong)NoDataView *noDataView;

@property(nonatomic,strong)NSMutableDictionary *dataDict;

@end

@implementation PrivateListViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];

    self.view.backgroundColor = BackGroundColor;
    
    
    if ([self.type isEqualToString:@"Appoint"]) {
        
     
        //右侧图片 icon_nbarmore
            UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_nbarmore"]
                                                                                       imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
            self.navigationItem.rightBarButtonItem = rightButtonItem;
    }
    
    self.title = @"选择私教课程";
    
    self.dataSource = [NSMutableArray arrayWithArray:[self.dict objectForKey:@"PrivateCourseName"]];
    
    [self createSubView];
    
}

#pragma mark 创建子视图
-(void)createSubView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[AppointPrivateClassTableViewCell class] forCellReuseIdentifier:@"AppointPrivateClassTableViewCell"];
    [tableView registerClass:[CoursesClassTableViewCell class] forCellReuseIdentifier:@"CoursesClassTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);        
    }];
    
    UIView *tableHeadView = [[UIView alloc] init];
    tableHeadView.backgroundColor = CSWhiteColor;
    UIImageView *teachHeadView = [[UIImageView alloc] init];
    teachHeadView.layer.masksToBounds = YES;
    teachHeadView.layer.cornerRadius = 3;
    teachHeadView.image = PlaceHold;
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[self.dict objectForKey:@"Pic"],mid_image];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [teachHeadView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
    
    [tableHeadView addSubview:teachHeadView];
    [teachHeadView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(tableHeadView).offset(30);
        make.left.mas_equalTo(tableHeadView).offset(20);
        make.width.height.mas_equalTo(60);
        make.bottom.mas_equalTo(tableHeadView).offset(-15);
    }];
    
    UILabel *teachLabel = [[UILabel alloc] init];
    teachLabel.font = MidBigFont;
    teachLabel.text = [self.dict objectForKey:@"TeachName"];
    teachLabel.textColor = CSColorFromRGB(0x0a0a0a);
    [tableHeadView addSubview:teachLabel];
    [teachLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(teachHeadView);
        make.left.mas_equalTo(teachHeadView.mas_right).offset(10);
    }];
    
    TTTAttributedLabel *detailLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero];
    [tableHeadView addSubview:detailLabel];
    detailLabel.font = SmallFont;
    detailLabel.numberOfLines = 0;
    detailLabel.lineBreakMode = NSLineBreakByCharWrapping;
    detailLabel.lineSpacing = 3;
    detailLabel.text = [[self.dict objectForKey:@"Introduction"] isNull]?@"暂无简介":[self.dict objectForKey:@"Introduction"];
    [tableHeadView addSubview:detailLabel];
    [detailLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(teachLabel.mas_bottom).offset(15);
        make.left.mas_equalTo(teachLabel);
    }];
    
    [self.view addSubview:tableHeadView];
    [tableHeadView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(tableView);
        
        make.left.width.mas_equalTo(self.view);
    }];
    
    [tableHeadView setNeedsLayout];
    [tableHeadView layoutIfNeeded];
    
    tableView.tableHeaderView = tableHeadView;
}


#pragma mark UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

#pragma mark UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 8;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *sectionHeadView = [[UIView alloc] init];
    
    sectionHeadView.backgroundColor = CSWhiteColor;
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = BackGroundColor;
    [sectionHeadView addSubview:lineView];
    [lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.mas_equalTo(sectionHeadView);
        make.height.mas_equalTo(10);
    }];
    
    /**
     教练名字
     */
    UILabel *coachLineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 30)];
    coachLineLabel.backgroundColor = ButtonBackGroundColor;
    [sectionHeadView addSubview:coachLineLabel];
    
    /**
     教练详情
     */
    UILabel *coachNameLabel = [[UILabel alloc] init];
    coachNameLabel.font = BoldMidBigFont;
    coachNameLabel.text = @"课程项目";
    [sectionHeadView addSubview:coachNameLabel];
    
    [coachLineLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lineView.mas_bottom).offset(17.5);
        make.left.mas_equalTo(sectionHeadView).offset(10);
        make.height.mas_equalTo(15);
        make.width.mas_equalTo(3);
    }];
    
    [coachNameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(coachLineLabel);
        make.left.mas_equalTo(coachLineLabel.mas_right).offset(5);
    }];
    
    return sectionHeadView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.type isEqualToString:@"Appoint"]) {
    
        AppointPrivateClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AppointPrivateClassTableViewCell"];
        
        NSDictionary *courseDict = [self.dataSource objectAtIndex:indexPath.section];
        
        CourseModel *courseModel = [CourseModel mj_objectWithKeyValues:courseDict];
        
        cell.courseModel = courseModel;
        
        [cell.appointBtn addTarget:self action:@selector(appointBtnClick:)];
        
        cell.appointBtn.tag = indexPath.row;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    else{
        
        CoursesClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoursesClassTableViewCell"];
        
        NSDictionary *courseDict = [self.dataSource objectAtIndex:indexPath.section];
        
        CourseModel *courseModel = [CourseModel mj_objectWithKeyValues:courseDict];
        
        cell.courseModel = courseModel;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}


#pragma mark 代约按钮点击
-(void)appointBtnClick:(UIButton *)btn{
    
    NSDictionary *courseDict = [self.dataSource objectAtIndex:btn.tag];
    
    [self.dataDict setObject:[NSString stringWithFormat:@"%@",[self.dict objectForKey:@"ID"]] forKey:@"coursePlanID"];
    
    [self.dataDict setObject:[courseDict objectForKey:@"ID"] forKey:@"courseID"];
    
    [self choseTime];
}


#pragma mark 选择时间
-(void)choseTime{
    
    [self.view endEditing:YES];
    
    __weak typeof(self)weakSelf = self;
    
    
    NSString *BeginDateTime = [NSString stringWithFormat:@"%@ %@",[self.dict objectForKey:@"BeginDate"],[self.dict objectForKey:@"BeginHour"]];

    NSString *endTime = [NSString stringWithFormat:@"%@ %@",[self.dict objectForKey:@"BeginDate"],[self.dict objectForKey:@"EndHour"]];
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器
    
    dateFormatter.dateFormat=@"yyyy-MM-dd HH:mm";//指定转date得日期格式化形式
    
    
    [[MOFSPickerManager shareManger] showDatePickerWithTag:135 firstDate:[dateFormatter dateFromString:BeginDateTime] minDate:[dateFormatter dateFromString:BeginDateTime] maxDate:[dateFormatter dateFromString:endTime] datePickerMode:UIDatePickerModeTime commitBlock:^(NSDate *date) {
        
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];//创建一个日期格式化器
        
        dateFormatter.dateFormat=@"HH:mm";//指定转date得日期格式化形式
        
        NSString *formatDate = [dateFormatter stringFromDate:date];
        
        [weakSelf.dataDict setObject:[NSString stringWithFormat:@"%@ %@",self.date,formatDate] forKey:@"beginDate"];
        
        [weakSelf.dataDict setObject:[NSString stringWithFormat:@"%@ %@",weakSelf.date,[weakSelf.dict objectForKey:@"EndHour"]] forKey:@"endDate"];
        
        [weakSelf selectVip];
        
    } cancelBlock:^{
        
    }];
    
}

#pragma mark 选择会员
-(void)selectVip{
    
    __weak typeof(self)weakSelf = self;
    
    SelectMemberViewController *selectMemberVC = [[SelectMemberViewController alloc] init];
    
    selectMemberVC.memberUrl = Get_MemberList;
    
    selectMemberVC.sendUserBlock = ^(UserAccount *userModel) {
        
        [weakSelf.dataDict setObject:userModel.MemberID forKey:@"memberID"];
        
        [weakSelf postPrivate];
    };
    
    UserNavigationController *naVC = [[UserNavigationController alloc] initWithRootViewController:selectMemberVC];
    
    [self presentViewController:naVC animated:NO completion:nil];
}


-(void)postPrivate{
    
    [MBProgressHUD showMessage:@"加载中.." toView:self.view];
    
    [HTTPTool POSTRaw:Post_PrivateCourseOrderOperate
           parameters:self.dataDict success:^(id responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
            
            [MBProgressHUD showText:@"操作成功"];
            
            for (UIViewController *temp in self.navigationController.viewControllers) {
                
                if ([temp isKindOfClass:[TeachPrivateClassViewController class]]) {
                    
                    [self.navigationController popToViewController:temp animated:YES];
                    
                    [NotificationCenter postNotificationName:@"reloadPrivateTeach" object:nil userInfo:nil];
                }
            }
            
        }
        else{
            
            [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
        }
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        [MBProgressHUD showText:@"添加失败"];
    }];
}

#pragma mark 右侧按钮点击
-(void)rightBtnClick{
    
    __weak typeof(self)weakSelf = self;
    
    HDAlertView *alertView = [HDAlertView showActionSheetWithTitle:nil];
    
    alertView.buttonsListStyle = HDAlertViewButtonsListStyleRows;
    
    [alertView addButtonWithTitle:@"删除当天全部课程" type:HDAlertViewButtonTypeCancel handler:^(HDAlertView *alertView) {
       
        [weakSelf deleteDateCourse];
        
    }];
    
    [alertView addButtonWithTitle:@"删除教练所有排课" type:HDAlertViewButtonTypeCancel handler:^(HDAlertView *alertView) {
        
        [weakSelf deleteAllCourse];
    }];
    
    [alertView addButtonWithTitle:@"取消" type:HDAlertViewButtonTypeDefault handler:^(HDAlertView *alertView) {
        
    }];
    
    [alertView show];
}


/**
 删除某天的课程
 */
-(void)deleteDateCourse{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    VenueModel *venueModel = [VenueModel venue];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:[self.dict objectForKey:@"ID"] forKey:@"coursePlanID"];
    
    [params setObject:self.date forKey:@"date"];
    
    [MBProgressHUD showMessage:@"加载中.." toView:self.view];
    
    [HTTPTool POSTRaw:Post_CancelCoursePlan
           parameters:params success:^(id responseObject) {
               
               [MBProgressHUD hideHUDForView:self.view];
               
               if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
                   
                   [MBProgressHUD showText:@"操作成功"];
                   
                   for (UIViewController *temp in self.navigationController.viewControllers) {
                       
                       if ([temp isKindOfClass:[TeachPrivateClassViewController class]]) {
                           
                           [self.navigationController popToViewController:temp animated:YES];
                           
                           [NotificationCenter postNotificationName:@"reloadPrivateTeach" object:nil userInfo:nil];
                       }
                   }
                   
               }
               else{
                   
                   [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
               }
               
           } failure:^(NSError *error) {
               
               [MBProgressHUD hideHUDForView:self.view];
               
               [MBProgressHUD showText:@"删除失败"];
           }];
}



/**
 删除全部课程
 */
-(void)deleteAllCourse{
    
    //NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    //[params setObject:[self.dict objectForKey:@"ID"] forKey:@"ID"];
    
    [MBProgressHUD showMessage:@"加载中.." toView:self.view];
    
    NSString *delUrl = [NSString stringWithFormat:@"%@/%@",Post_DelCoursePlan,[self.dict objectForKey:@"ID"]];
    
    [HTTPTool POSTRaw:delUrl
           parameters:self.dataDict success:^(id responseObject) {
               
               [MBProgressHUD hideHUDForView:self.view];
               
               if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){
                   
                   [MBProgressHUD showText:@"操作成功"];
                   
                   for (UIViewController *temp in self.navigationController.viewControllers) {
                       
                       if ([temp isKindOfClass:[TeachPrivateClassViewController class]]) {
                           
                           [self.navigationController popToViewController:temp animated:YES];
                           
                           [NotificationCenter postNotificationName:@"reloadPrivateTeach" object:nil userInfo:nil];
                       }
                   }
                   
               }
               else{
                   
                   [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
               }
               
           } failure:^(NSError *error) {
               
               [MBProgressHUD hideHUDForView:self.view];
               
               [MBProgressHUD showText:@"删除失败"];
           }];
}

-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}

#pragma mark Get
-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

-(NSMutableDictionary *)dataDict{
    
    if (!_dataDict) {
        
        _dataDict = [[NSMutableDictionary alloc] init];
    }
    
    return _dataDict;
}

@end
